package com.igeek.health.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.igeek.health.constant.MessageConstant;
import com.igeek.health.result.Result;
import com.igeek.health.utils.JwtHelper;
import com.igeek.health.utils.WebUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author fengqq
 * @Description 自定义拦截器--解析token
 * @Date 2024/9/13  10:32
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中 判断 是否携带 token 如果不存在则403
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            //将result对象 转换为 json格式字符串 再使用response响应给客户端
            Result result = new Result(false, MessageConstant.TOKEN_EMPTY, 403);
            WebUtils.renderString(response, JSONUtil.toJsonStr(result));
            return false;
        }
        //2.请求头中解析token 有没有会员id  如果不存在则403
        Integer memberId = JwtHelper.getMemberId(token);
        if(memberId==null){
            //将result对象 转换为 json格式字符串 再使用response响应给客户端
            Result result = new Result(false, MessageConstant.TOKEN_VERIFY_FAIL, 403);
            WebUtils.renderString(response, JSONUtil.toJsonStr(result));
            return false;
        }
        //3.将会员id存放到request请求属性中 放行到controller
        request.setAttribute("memberId",memberId);
        return true;
    }
}
